package command

import (
	"fmt"
	"gitee.com/zackeus/go-boot/freeswitch/esl/headers"
	"gitee.com/zackeus/goutil/strutil"
	"net/textproto"
	"strconv"
	"strings"
)

// Event 订阅事件
// event plain ALL
// event plain CHANNEL_CREATE CHANNEL_DESTROY CUSTOM conference::maintenance sofia::register sofia::expire
// event xml ALL
// event json CHANNEL_ANSWER
type Event struct {
	Ignore bool
	Format string
	Listen []string
}

type MyEvents struct {
	Format string
	UUID   string
}

type DisableEvents struct{}

// DivertEvents The divert_events command is available to allow events that an embedded script would expect to get in the inputcallback to be diverted to the event socket.
type DivertEvents struct {
	Enabled bool
}

type SendEvent struct {
	Name    string
	Headers textproto.MIMEHeader
	Body    string
}

func (e Event) BuildCmd() string {
	/* 取消订阅操作 */
	prefix := ""
	if e.Ignore {
		prefix = "nix"
	}

	if strutil.IsBlank(e.Format) {
		e.Format = "plain"
	}
	return fmt.Sprintf("%sevent %s", prefix, e.Format)
}

func (e Event) BuildMessage() string {
	/* 取消订阅操作 */
	prefix := ""
	if e.Ignore {
		prefix = "nix"
	}

	if strutil.IsBlank(e.Format) {
		e.Format = "plain"
	}
	return fmt.Sprintf("%sevent %s %s", prefix, e.Format, strings.Join(e.Listen, " "))
}

func (m MyEvents) BuildCmd() string {
	return "myevents"
}

func (m MyEvents) BuildMessage() string {
	if len(m.UUID) > 0 {
		return fmt.Sprintf("myevents %s %s", m.Format, m.UUID)

	}
	return fmt.Sprintf("myevents %s", m.Format)
}

func (DisableEvents) BuildCmd() string {
	return "noevents"
}

func (DisableEvents) BuildMessage() string {
	return "noevents"
}

func (d DivertEvents) BuildCmd() string {
	if d.Enabled {
		return "divert_events on"
	}
	return "divert_events off"
}

func (d DivertEvents) BuildMessage() string {
	if d.Enabled {
		return "divert_events on"
	}
	return "divert_events off"
}

func (s *SendEvent) BuildCmd() string {
	return "sendevent"
}

func (s *SendEvent) BuildMessage() string {
	// Ensure the correct content length is set in the header
	if len(s.Body) > 0 {
		s.Headers.Set(headers.ContentLength, strconv.Itoa(len(s.Body)))
	} else {
		delete(s.Headers, headers.ContentLength)
	}

	// Format the headers
	headerString := FormatHeaderString(s.Headers)
	if _, ok := s.Headers[headers.ContentLength]; ok {
		return fmt.Sprintf("sendevent %s\r\n%s\r\n\r\n%s", s.Name, headerString, s.Body)
	}
	return fmt.Sprintf("sendevent %s\r\n%s", s.Name, headerString)
}
